package hos.net.soap

import com.drake.net.request.tagOf
import hos.net.soap.exception.SoapXmlException
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import org.ksoap2.serialization.SoapSerializationEnvelope

/**
 * <p>Title: SoapNetInterceptor </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-04-08 20:55
 * @version : 1.0
 */
object SoapNetInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val soapRequest =
            request.tagOf<SoapSerializationEnvelope>() ?: return chain.proceed(request)
        val response = chain.proceed(request)
        try {
            val body = response.body ?: return response
            val result = soapRequest.parseResponse(body.byteStream())
            if (result == null) {
                val responseBody = "".toResponseBody(body.contentType())
                return response.newBuilder().body(responseBody).build()
            }
            val responseBody = result.toString().toResponseBody(body.contentType())
            return response.newBuilder().body(responseBody).build()
        } catch (e: Exception) {
            throw SoapXmlException(response, "xml parse exception", e, soapRequest)
        }
    }
}